package org.ThreadDemo.juctool;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo01 {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("HH:mm:ss---");
        Semaphore semaphore = new Semaphore(3);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(df.format(new Date()) + Thread.currentThread().getName() + " got resource");
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    //System.out.println(df.format(new Date()) + Thread.currentThread().getName() + " resource resource");
                }
            }
        };

        for (int i = 0; i < 9; i++) {
            new Thread(runnable, "Thread" + i).start();
        }
    }
}
